from PIL import Image, ImageDraw, ImageFont, ImageEnhance, ImageColor
import uuid
import os
from config import Config

def parse_size(size_str):
    """解析尺寸参数"""
    if not size_str:
        return None
    parts = size_str.split('x')
    if len(parts) != 2:
        raise ValueError("尺寸格式应为 WIDTHxHEIGHT")
    try:
        width = int(parts[0]) if parts[0] else None
        height = int(parts[1]) if parts[1] else None
    except ValueError:
        raise ValueError("尺寸必须为整数")
    return (width, height)

def resize_image(image, target_size):
    """调整图片尺寸"""
    original_width, original_height = image.size
    target_width, target_height = target_size

    if target_width and target_height:
        new_size = (target_width, target_height)
    elif target_width:
        ratio = target_width / original_width
        new_height = int(original_height * ratio)
        new_size = (target_width, new_height)
    elif target_height:
        ratio = target_height / original_height
        new_width = int(original_width * ratio)
        new_size = (new_width, target_height)
    else:
        return image

    return image.resize(new_size, Image.LANCZOS)

def add_text_watermark(image, text, font_path, font_size, color, position, opacity):
    """添加文字水印"""
    if image.mode != 'RGBA':
        image = image.convert('RGBA')
    
    txt = Image.new('RGBA', image.size, (0, 0, 0, 0))
    draw = ImageDraw.Draw(txt)
    font = ImageFont.truetype(font_path, font_size)
    text_width, text_height = draw.textbbox((0, 0), text, font=font)[2:]
    
    # 计算位置坐标
    width, height = image.size
    if position == 'top_left':
        x, y = 10, 10
    elif position == 'top_right':
        x = width - text_width - 10
        y = 10
    elif position == 'bottom_left':
        x = 10
        y = height - text_height - 10
    elif position == 'bottom_right':
        x = width - text_width - 10
        y = height - text_height - 10
    elif position == 'center':
        x = (width - text_width) // 2
        y = (height - text_height) // 2
    else:
        raise ValueError("无效的位置参数")
    
    # 应用透明度
    text_color = (*color, int(opacity * 255))
    draw.text((x, y), text, font=font, fill=text_color)
    
    return Image.alpha_composite(image, txt).convert('RGB')

def add_image_watermark(image, watermark_path, position, opacity):
    """添加图片水印"""
    watermark = Image.open(watermark_path).convert("RGBA")
    watermark = ImageEnhance.Brightness(watermark).enhance(opacity)
    
    w_width, w_height = watermark.size
    img_width, img_height = image.size
    
    # 计算位置坐标
    if position == 'top_left':
        pos = (10, 10)
    elif position == 'top_right':
        pos = (img_width - w_width - 10, 10)
    elif position == 'bottom_left':
        pos = (10, img_height - w_height - 10)
    elif position == 'bottom_right':
        pos = (img_width - w_width - 10, img_height - w_height - 10)
    elif position == 'center':
        pos = ((img_width - w_width) // 2, (img_height - w_height) // 2)
    else:
        raise ValueError("无效的位置参数")
    
    if image.mode != 'RGBA':
        image = image.convert('RGBA')
    
    image.paste(watermark, pos, watermark)
    return image.convert('RGB')

def allowed_file(filename):
    """检查文件扩展名是否允许"""
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in Config.ALLOWED_EXTENSIONS